package utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.util.NoSuchElementException;
import java.util.Stack;



/**
 * 当前进程 Activity 管理，用于安全退出程序。
 * （关闭所有打开的 Activity 再退出）
 * （需要事先在Activity的onCreate中调用 AppActivities.add 方法，以及结束时使用 AppActivities.finish 来结束）
 *
 * Created by jiangwj on 2014/7/29.
 */
public final class AppActivities {

    private static AppActivities _instance = new AppActivities();

    public static AppActivities instance() {
        return _instance;
    }

    // 当前程序中运行的所有 activities
    private Stack<Activity> allActivities = new Stack<Activity>();

    /**
     * 将 Activity 添加到列表
     *
     * @param act
     */
    public void add(Activity act) {
        allActivities.add(act);
    }

    /**
     * 将指定 Activity 移除
     */
    public void remove(Activity act) {
        if (act != null) {
            allActivities.remove(act);
        }
    }

    public boolean isAlive(Activity act) {
        int postion = -1;
        if (act != null) {
            postion = allActivities.search(act);
        }
        return postion == -1 ? false : true;
    }

    /**
     * 结束一个 Activity，并将其移除
     */
    public void finish(Activity act) {
        if (act != null) {
            act.finish();
            allActivities.remove(act);
            Log.e("finish", "finish 调用");
        }
    }

    /**
     * 使用 requestCode 结束一个 Activity
     *
     * @param act
     * @param requestCode
     */
    public void finish(Activity act, int requestCode) {
        if (act != null) {
            act.finishActivity(requestCode);
            allActivities.remove(act);
        }
    }

    /**
     * 获取当前 activity
     *
     * @return
     */
    public Activity current() {
        if (allActivities.size() == 0) {
            return null;
        }
        try {
            return allActivities.lastElement();
        } catch (NoSuchElementException ex) {
            return null;
        }
    }

    public Activity secondActivity() {
        if (allActivities.size() < 2) {
            return null;
        }
        try {
            return allActivities.get(allActivities.size() - 2);
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }
    }

    /**
     * 从当前Activity一直结束到指定Activity
     *
     * @param clz class of Activity
     */
    public void finishTo(Context context, Class<? extends Activity> clz) {
        context = context.getApplicationContext();
        Activity cur = current();
        while (cur != null) {
            if (cur.getClass().equals(clz)) {
                return;
            }
            finish(cur);
            cur = current();
        }
        // not found in list
        Intent intent = new Intent(context, clz);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 从当前Activity一直结束到指定Activity,并且可以携带参数
     * @param clz  class of Activity
     */
    public void finishTo(Context context, Class<? extends Activity> clz, String username, String password, boolean passwordEncode) {
        Activity cur = current();
        while (cur != null) {
            if (cur.getClass().equals(clz)) {
                Log.e("password", "return finish : " + cur.getClass().getCanonicalName());
                return;
            }
            Log.e("password", "finish : " + cur.getClass().getCanonicalName());
            finish(cur);
            cur = current();
        }
        // not found in list
        Intent intent = new Intent(context, clz);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

//        intent.setAction(SipLoginActivity.ACTION_OPEN);
//        intent.putExtra(SipLoginActivity.EXTRA_USERNAME, username);
//        intent.putExtra(SipLoginActivity.EXTRA_PASSWORD, password);
//        intent.putExtra(SipLoginActivity.EXTRA_DO_ACTION, SipLoginActivity.DO_ACTION_AUTO_LOGIN);
//        intent.putExtra(SipLoginActivity.EXTRA_PASSWORD_ENCODE, passwordEncode);

        context.startActivity(intent);
    }

    public void finishTopInclude(Class<? extends Activity> clazz) {
        boolean hasActivity = false;
        for (int i = allActivities.size() - 1; i >= 0; i--) {
            Activity activity = allActivities.get(i);
            if (activity.getClass().equals(clazz)) {
                hasActivity = true;
                break;
            }
        }
        if (hasActivity) {
            do {
                Activity current = current();
                if (current == null) {
                    break;
                }
                if (current.getClass().equals(clazz)) {
                    finish(current);
                    break;
                } else {
                    finish(current);
                }
            } while (true);
        }

    }

    /**
     * 是否已经开启
     */
    public boolean contains(Class<? extends Activity> clazz) {
        for(Activity activity : allActivities) {
            if (activity.getClass().equals(clazz)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 完全退出程序
     */
    public void finishAll() {
        // 先关闭所有打开的 Activity
        for (Activity act : allActivities) {
            act.finish();
        }
        allActivities.clear();
    }

}
